package product

import (
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	error2 "OnlineRetailers/models/errorDeal"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"os"
)

type DeleteProductDetailed struct {
	beego.Controller
}

func (c *DeleteProductDetailed) DeleteProductDetailed() {

	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Product/DeleteProductDetailed"
	//res := resMes.GetAdminUser{}
	//user := []*Admin.User{}
	log := &error2.Log{}
	mes := &error2.Mes{}
	var err error
	o := orm.NewOrm()

	id := c.GetString("id")
	err = session2.CheckSession(c.Ctx.Request.Header["Session"], 1)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	err = DeleteClassM2M(o, id)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	productDetailed := &Admin.ProductDetailed{ProductId: id}
	err = o.Read(productDetailed)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	DeleteClassImg(productDetailed)

	num, err := o.QueryTable("ProductDetailed").Filter("ProductId__exact", id).Delete()
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	} else if num == 0 {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "400", "失败")
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}

func DeleteClassM2M(o orm.Ormer, id string) (err error) {

	sql := "delete from `classification_product_detaileds` where `product_detailed_id`=?"
	_, err = o.Raw(sql, id).Exec()
	if err != nil {

		return
	}

	return nil
}

func DeleteClassImg(productDetailed *Admin.ProductDetailed) {
	if productDetailed.PrimariesImage != "" {
		_ = os.Remove("." + productDetailed.PrimariesImage)

	}
	if productDetailed.CarouselImage1 != "" {
		_ = os.Remove("." + productDetailed.CarouselImage1)

	}
	if productDetailed.CarouselImage2 != "" {
		_ = os.Remove("." + productDetailed.CarouselImage2)

	}
	if productDetailed.DetailedImage1 != "" {
		_ = os.Remove("." + productDetailed.DetailedImage1)

	}
	if productDetailed.DetailedImage2 != "" {
		_ = os.Remove("." + productDetailed.DetailedImage2)

	}
	if productDetailed.DetailedImage3 != "" {
		_ = os.Remove("." + productDetailed.DetailedImage3)

	}
	if productDetailed.DetailedImage4 != "" {
		_ = os.Remove("." + productDetailed.DetailedImage4)

	}
	if productDetailed.DetailedImage5 != "" {
		_ = os.Remove("." + productDetailed.DetailedImage5)

	}

	if productDetailed.DetailedImage6 != "" {
		_ = os.Remove("." + productDetailed.DetailedImage6)

	}

	if productDetailed.DetailedImage7 != "" {
		_ = os.Remove("." + productDetailed.DetailedImage7)

	}
}
